package com.personal.portal.admin.service.impl;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.personal.portal.common.entity.Result;
import com.personal.portal.common.entity.SkillLevel;
import com.personal.portal.admin.entity.Skill;
import com.personal.portal.admin.mapper.SkillMapper;
import com.personal.portal.admin.service.SkillService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 技能服务实现类
 *
 * @author zhanghui
 * @version 1.0.0
 * @since 2025-11-10
 */
@Service
public class SkillServiceImpl implements SkillService {

    @Resource
    private SkillMapper skillMapper;

    @Override
    public Skill queryById(Long id) {
        validateId(id);
        return skillMapper.selectOneById(id);
    }

    @Override
    public Skill queryByEntity(Skill skill) {
        QueryWrapper queryWrapper = buildQueryWrapper(skill);
        return skillMapper.selectOneByQuery(queryWrapper);
    }

    @Override
    public List<Skill> queryList(Skill skill) {
        QueryWrapper queryWrapper = buildQueryWrapper(skill);
        return skillMapper.selectListByQuery(queryWrapper);
    }

    @Override
    public Result.PageResult<Skill> queryPage(int pageNum, int pageSize, Skill skill) {
        QueryWrapper queryWrapper = buildQueryWrapper(skill);
        Page<Skill> paginate = skillMapper.paginate(pageNum, pageSize, queryWrapper);
        return new Result.PageResult<>(paginate.getRecords(), paginate.getTotalRow(), pageNum, pageSize);
    }

    @Override
    public int insert(Skill skill) {
        validateAndCalculateSkill(skill);
        return skillMapper.insert(skill);
    }

    @Override
    public int update(Skill skill) {
        if (skill.getId() == null) {
            throw new IllegalArgumentException("技能ID不能为空");
        }
        validateId(skill.getId());
//        validateAndCalculateSkill(skill);

        Skill existing = skillMapper.selectOneById(skill.getId());
        if (existing == null) {
            throw new IllegalArgumentException("技能信息不存在");
        }

        return skillMapper.update(skill);
    }

    @Override
    public int deleteById(Long id) {
        validateId(id);

        Skill existing = skillMapper.selectOneById(id);
        if (existing == null) {
            throw new IllegalArgumentException("技能信息不存在");
        }

        return skillMapper.deleteById(id);
    }

    @Override
    public List<Long> deleteBatch(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new IllegalArgumentException("ID列表不能为空");
        }

        List<Long> successIds = new ArrayList<>();
        List<Long> failedIds = new ArrayList<>();

        for (Long id : ids) {
            try {
                validateId(id);

                Skill existing = skillMapper.selectOneById(id);
                if (existing == null) {
                    failedIds.add(id);
                    continue;
                }

                int result = skillMapper.deleteById(id);
                if (result > 0) {
                    successIds.add(id);
                } else {
                    failedIds.add(id);
                }
            } catch (Exception e) {
                failedIds.add(id);
            }
        }

        if (!successIds.isEmpty()) {
            return successIds;
        } else {
            throw new IllegalArgumentException("批量删除失败");
        }
    }

    private void validateAndCalculateSkill(Skill skill) {
        if (skill == null) {
            throw new IllegalArgumentException("技能信息不能为空");
        }
        if (StringUtils.isBlank(skill.getName())) {
            throw new IllegalArgumentException("技能名称不能为空");
        }

        // 自动计算技能等级
        if (skill.getProficiencyLevel() != null) {
            String calculatedLevel = calculateSkillLevel(skill);
            skill.setLevel(calculatedLevel);
        }

        // 验证技能等级一致性（如果手动设置）
        if (StringUtils.isNotBlank(skill.getLevel()) && skill.getProficiencyLevel() != null) {
            String expectedLevel = calculateSkillLevel(skill);
            if (!expectedLevel.equals(skill.getLevel())) {
                throw new IllegalArgumentException("技能等级与熟练度不匹配：熟练度" + skill.getProficiencyLevel() + "分应该对应" + expectedLevel + "等级");
            }
        }
    }

    /**
     * 重新计算技能的等级
     *
     * @param skill 技能实体
     * @return 更新后的技能等级
     */
    public String calculateSkillLevel(Skill skill) {
        if (skill.getProficiencyLevel() == null) {
            return null;
        }
        return SkillLevel.calculateLevel(skill.getProficiencyLevel());
    }

    private void validateId(Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("无效的技能ID");
        }
    }

    private QueryWrapper buildQueryWrapper(Skill skill) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(Skill::getId, skill.getId(), skill.getId() != null);
        queryWrapper.like(Skill::getName, skill.getName(), StringUtils.isNotEmpty(skill.getName()));
        queryWrapper.like(Skill::getDescription, skill.getDescription(), StringUtils.isNotEmpty(skill.getDescription()));
        queryWrapper.eq(Skill::getCategoryId, skill.getCategoryId(), skill.getCategoryId() != null);
        queryWrapper.eq(Skill::getLevel, skill.getLevel(), StringUtils.isNotEmpty(skill.getLevel()));
        queryWrapper.eq(Skill::getIsCore, skill.getIsCore(), skill.getIsCore() != null);

        queryWrapper.orderBy(Skill::getSortOrder, true);
        queryWrapper.orderBy(Skill::getId, true);
        return queryWrapper;
    }
}